package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.vos.NewsVo;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.KeeperException;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsAutoScanServiceImpl wmNewsAutoScanServiceImpl;
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate; // kafka客户端

    /**
     * 自媒体端 文章列表分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult getNewsList(WmNewsPageReqDto dto) {
        if (dto == null) throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        //1.参数校验
        dto.checkParam();//分页检查

        //2.条件分页查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = Wrappers.<WmNews>lambdaQuery();
        //2.1状态精确查询
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //2.2频道精确查
        if (dto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //2.3时间范围查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        //2.4关键字模糊查询
        if (dto.getKeyword() != null) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //2.5当前登录用户精确查询
        lambdaQueryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        //2.6按照发布时间倒序查询
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        //查询数据
        page(page, lambdaQueryWrapper);
        ResponseResult pageResponseResult = new PageResponseResult((int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());
        pageResponseResult.setCode(AppHttpCodeEnum.SUCCESS.getCode());
        pageResponseResult.setErrorMessage(AppHttpCodeEnum.SUCCESS.getErrorMessage());
        //3.返回结果
        return pageResponseResult;
    }


    /**
     * 发布文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //0.入参校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = new WmNews();
        //属性拷贝
        BeanUtils.copyProperties(dto, wmNews);

        //数据处理
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            wmNews.setImages(StringUtils.join(dto.getImages(), ","));
        }
        //文章封面图片布局
        if (dto.getType() == -1) {
            wmNews.setType(null); // 封面图片为自动,先给type置为null
        }
        wmNews.setSubmitedTime(new Date());//设置提交/修改时间
        wmNews.setEnable((short) 1); //默认上架
        //1.根据id判断是新增或者修改文章
        saveOrUpdateNews(wmNews);

        //2.是否为草稿,是草稿就直接返回,流程结束
        if (wmNews.getStatus() == WmNews.Status.NORMAL.getCode()) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //3.不是草稿,需要处理内容图片与素材的关联关系
        //3.1提前文章内容中的所有图片url
        List<String> imageUrlList = parseImageUrl(dto.getContent());

        //3.2向wm_news_material中间表中插入数据
        saveRelation4Content(imageUrlList, wmNews.getId());

        //4.不是草稿,需要处理封面图片与素材的关联关系 ,如果封面布局是自动,需要到内容中匹配封面图片
        saveRelationInfo4Cover(dto, wmNews, imageUrlList);

        //异步调用进行 审核文章
//        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());

        //TODO 进行延迟审核处理 (异步方式添加审核任务)
        wmNewsTaskService.addNewsToTask(wmNews.getId(), dto.getPublishTime());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 保存文章封面图片与素材的关系
     * 功能1:如果封面设置的是自动模式,需要根据内容中的图片数据来为封面匹配图片
     * a.如果文章内容中图片大于等于3  多图模式 settype = 3
     * b.如果文章内容图片大于等于1 小于3, 单图模式 settype = 1
     * c.如果文章内容中图片数量=0, 无图模式 ,settype = 0
     * <p>
     * 功能2:保存封面图片与素材的关联
     *
     * @param dto
     * @param wmNews
     * @param imageUrlList 文章中所有的图片url
     */
    private void saveRelationInfo4Cover(WmNewsDto dto, WmNews wmNews, List<String> imageUrlList) {
        //1拿到前端传的封面图片数据
        List<String> images = dto.getImages();

        if (dto.getType() == WemediaConstants.WM_NEWS_TYPE_AUTO) {

            if (imageUrlList.size() >= 3) {
                //多图
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = imageUrlList.stream().limit(3).collect(Collectors.toList());
            } else if (imageUrlList.size() >= 1 && imageUrlList.size() < 3) {
                //单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = imageUrlList.stream().limit(1).collect(Collectors.toList());
            } else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            if (images != null && images.size() > 0) {
                wmNews.setImages(StringUtils.join(images, ","));
            }
            //更新文章表
            updateById(wmNews);

            //保存封面图片与素材的关联关系
            if (images != null && images.size() > 0) {
                saveRelationWithImage(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
            }
        }
    }

    /**
     * 保存文章内容图片 与 素材关系
     *
     * @param imageUrlList
     * @param newsId       文章id
     */
    private void saveRelation4Content(List<String> imageUrlList, Integer newsId) {
        saveRelationWithImage(imageUrlList, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存文章与图片素材的关联关系,操作数据库wm_news_material表
     *
     * @param imageUrlList
     * @param newsId
     * @param type
     */
    private void saveRelationWithImage(List<String> imageUrlList, Integer newsId, Short type) {
        //1.入参校验
        if (imageUrlList.size() > 0 && imageUrlList != null && newsId != null) {
            //2.根据图片的url查询对应的素材id聚合
            List<WmMaterial> dbMaterials =
                    wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imageUrlList));
            List<Integer> materialIds = dbMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

            if (materialIds.size() != imageUrlList.size()) {
                //数据库中查询的图片数量与文章中的图片数据不匹配,说明有脏数据 ,抛出异常,进行数据回滚
                throw new CustomException(AppHttpCodeEnum.MATERIALS_REFERENCE_FAIL);
            }

            //3.向wm_news_material表中插入数据
            wmNewsMaterialMapper.saveRelations(materialIds, newsId, type);
        }

    }

    /**
     * 提前文章内容中的所有图片的url
     *
     * @param content
     * @return
     */
    private List<String> parseImageUrl(String content) {
        List<String> imagesList = new ArrayList<>();

        JSONArray jsonArray = JSON.parseArray(content);
        //遍历json数组,取出每一个json
        for (Object json : jsonArray) {
            JSONObject jsonObject = JSON.parseObject(json.toString());
            if (jsonObject.get("type").equals("image")) {
                imagesList.add(jsonObject.get("value").toString());
            }
        }
        return imagesList;
    }

    /**
     * 新增或修改文章
     *
     * @param wmNews
     */
    private void saveOrUpdateNews(WmNews wmNews) {
        if (wmNews.getId() != null) {
            //修改
            //先删除当前文章与素材的关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        } else {
            //新增
            wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
            wmNews.setCreatedTime(new Date());

            save(wmNews);
        }
    }

    /**
     * 自媒体文章上下架  0:下架 1:上架
     * 自媒体端完成上架下后, 向kafka中发送一条消息由app文章微服务来监听对应下架文章.
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUpNews(WmNewsDto dto) {
        //1.入参校验
        if (dto.getId() == null || dto.getEnable() == null || (dto.getEnable() != 0 && dto.getEnable() != 1)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.判断文章状态(已发布)
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章未发表,无法进行上下架操作!");
        }
        //4.更新文章enable
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, wmNews.getId())
                .set(WmNews::getEnable, dto.getEnable()));

        //5.TODO 向kafka发送消息,由app端文章微服务来进行消费
        if (wmNews.getArticleId() != null) {
            Map map = new HashMap();
            map.put("articleId", wmNews.getArticleId());
            map.put("enable", dto.getEnable());

            kafkaTemplate.send(WemediaConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 平台管理端:查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult getNewsWithAuthorName(NewsAuthDto dto) {
        //1.入参校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页条件检查
        dto.checkParam();
//
//        //2.条件查询
//        List<NewsVo> newsVoList = wmNewsMapper.getNewsByCondition(dto);
//
//        //3.响应结果
//        return ResponseResult.okResult(newsVoList);
        Page<NewsVo> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<NewsVo> resPage = wmNewsMapper.getNewsByCondition2(page, dto);
//page()
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) resPage.getTotal());
        pageResponseResult.setData(resPage.getRecords());

        return pageResponseResult;
    }

    /**
     * 根据id查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult getOneNews(Integer id) {
        //1入参校验
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        NewsAuthDto dto = new NewsAuthDto();
        dto.setId(id);
        dto.setPage(1);
        dto.setSize(10);
        //2.调用mapper
        List<NewsVo> newsByConditionList = wmNewsMapper.getNewsByCondition(dto);
        if (newsByConditionList != null && newsByConditionList.size() > 0) {
            //3.响应结果
            return ResponseResult.okResult(newsByConditionList.get(0));
        }
        return null;
    }


    /**
     * 人工审核自媒体文章失败
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authNewsFail(NewsAuthDto dto) {
        //1入参校验
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        wmNewsMapper.authNewsByCondition(dto);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 人工审核文章通过
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authNewsPass(NewsAuthDto dto) {
        //1入参校验
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.setMsg("人工审核通过");
        wmNewsMapper.authNewsByCondition(dto);

        //发起远程feign调用app端文章微服务保存文章
        log.info("人工审核文章通过,开始feign调用app端保存文章....");
        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        try {
            //.如果审核都OK,远程调用app端的feign接口来保存文章内容
            ResponseResult result = wmNewsAutoScanServiceImpl.saveArticle(wmNews);
            if (result.getCode() == 200) {
                //远程调用相应ok
                wmNews.setArticleId((Long) result.getData());//回填article_id
                wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
                wmNewsMapper.updateById(wmNews);
            } else {
                throw new RuntimeException("WmNewsServiceImpl-feign远程调用-app端文章-同步保存失败!!");
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new RuntimeException("WmNewsServiceImpl-feign远程调用-app端文章-同步保存失败!!");
        }
        log.info("人工审核文章通过,feign调用app端保存文章结束over....");

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
